package chordcows;
import java.io.Serializable;
import java.rmi.*;
import java.rmi.registry.*;
import java.util.ArrayList;
import java.util.Set;

import de.uniba.wiai.lspi.chord.service.Chord;
import de.uniba.wiai.lspi.chord.service.ServiceException;

/**
 *
 * @author chris day & joshua sayers
 * @assignment assignment6
 */
public class RMIserver extends java.rmi.server.UnicastRemoteObject implements RMIreceiver {
	private int Port;
	private String Directory;
	public Registry registry;
	private Chord chord=null;
	private FileServer fileserver;

	public boolean receiveMessage(String filename) throws RemoteException {
		
		String[][] servers=null;
		System.out.println("Attempting to download " + filename + "...");
		
		try{
			servers = getSeederAddresses(filename);
		}catch(ServiceException e){e.printStackTrace();}
		
		
		Boolean downloaded = TransferClient.download(Directory, filename, servers);
	
		if (downloaded) {
			//seed file
			fileserver.seedFile(filename);
			return true;
		}
		else
		{
			System.out.println("WARNING: Could not find a copy of file: "+filename);
			System.out.println(filename+" not downloaded");
		}
			
		/* TODO
		* Code to remove file from chord network.
		 */
		
		return false;
	}
	
	public String[][] getSeederAddresses(String filename) throws ServiceException{
		Set<Serializable> IPs = null;
		IPs = chord.retrieve(new StringKey(filename));
		ArrayList<String> list = new ArrayList<String>();
		
		for(Serializable ip: IPs)
			list.add((String)ip);
		String[][] servers = new String[2][list.size()];
		String[] split;
		for(int x=0;x<list.size();x++){
			split = list.get(x).split("\\*");
			servers[0][x]=split[0];
			servers[1][x]=split[1];
		}
		
		return servers;
	}

	public RMIserver(String directory, Chord chord, FileServer fileserver, int port) throws RemoteException {
		this.Port = port;
		this.chord = chord;
		this.fileserver = fileserver;
		this.Directory = directory;
        	try {
        		registry = LocateRegistry.createRegistry(this.Port);
            		registry.rebind("RMIserver", this);
		} catch (RemoteException e) {
        		throw e;
        	}
    	}

    	public RMIserver(String directory, Chord chord, FileServer fileserver) throws RemoteException {
		this.Port = 8484;
		this.chord = chord;
		this.fileserver = fileserver;
		this.Directory = directory;
        	try {
        		registry = LocateRegistry.createRegistry(this.Port);
            		registry.rebind("RMIserver", this);
		} catch (RemoteException e) {
        		throw e;
        	}
    	}

    	static public void main(String args[]) {
        	try {
        		RMIserver s = new RMIserver("/Users/cjour/drop/", null, null);
        		System.out.println("done");
		} catch (Exception e) {
			System.out.println("dead");
           		System.exit(1);
    		}
     	}
}
